![]() |
Essentials of C++: Section IX |
Declaring New Types Using typedef and enum A. Typedef's
In its simplest usage the 'typedef' works as a synonym creator,
allowing the programmer to create meaningful type names for variations of
existing types. For example, there is no built-in Boolean type. Since
FALSE in C++ is defined as 0 while TRUE is defined as any other value, say
1, one could define the type Boolean as: This creates a new type called 'Boolean' whose instances simply hold
values of type integer. We can then add the code:
and make it our practice to use only the two values TRUE and FALSE with
variables of type 'Boolean'. Note that this new type name can be used
anywhere a built-in type name is used. The same form can be used to create types that are a bit more of an
extension of the C++ type system. For example, to define a type that
represents an array of 30 characters one would write: This creates a new type called 'String30' that represents an array of
31 characters - with the 31st character used to hold the null character.
Such types make it possible to declare formal parameters as variables of
specific array types as in: B. Enumerated Types For example: The enumerations are in upper case not because such is required by C++
but because they represent numeric constants. In other words, they can be
considered 'named constants' which, by the style rules used here, are
written in upper case. By default, the first one has the value 0, the
second one, 1 etc. One can change an enumerator's value by writing: inside the brackets as in: although it is unusual to care what value the enumerators have. To use enumerated types, the same type declaration format is used as
in: The variable 'act' can now hold the values 'CLOWN', 'ACROBAT',
'JUGGLER', and 'LION_TAMER'. Although 'act' can be seen as a variable that
holds integers, it is illegal to write the code: Note that the enumerators are NOT strings. If one writes the code: the output will be '5', not 'CLOWN'. Links to 'The Story of C++" and other documents
|